﻿using System.ComponentModel;
using System.Windows.Forms;
using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Views
{
	public partial class DocumentDetailsView : UserControl
	{
		public DocumentDetailsView()
		{
			this.InitializeComponent();
			this.UpdateView();
		}

		private DocumentPresenter presenter;
		public DocumentPresenter Presenter
		{
			get { return this.presenter; }
			set
			{
				if (value == this.presenter) return;
				if (this.presenter != null)
				{
					this.DetachPresenter();
				}

				this.presenter = value;

				if (this.presenter != null)
				{
					this.AttachPresenter();
				}
			}
		}

		private void AttachPresenter()
		{
			this.presenter.PropertyChanged += OnDocumentPropertyChanged;
			this.presenter.Schema.PropertyChanged += OnSchemaPropertyChanged;
			this.presenter.Style.PropertyChanged += OnStylePropertyChanged;
			this.UpdateView();
		}

		private void DetachPresenter()
		{
			this.presenter.PropertyChanged -= OnDocumentPropertyChanged;
			this.presenter.Schema.PropertyChanged -= OnSchemaPropertyChanged;
			this.presenter.Style.PropertyChanged -= OnStylePropertyChanged;
		}

		private void OnDocumentPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Name") this.UpdateView();
		}

		private void OnSchemaPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Name") this.UpdateView();
		}

		private void OnStylePropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Name") this.UpdateView();
		}

		private void UpdateView()
		{
			if (this.Presenter == null)
			{
				this.documentName.Text = "[nothing]";
				this.schemaName.Text = "[nothing]";
				this.styleName.Text = "[nothing]";
			}
			else
			{
				this.documentName.Text = string.IsNullOrEmpty(this.Presenter.Name) ? "[unsaved document]" : this.Presenter.Name;
				this.schemaName.Text = string.IsNullOrEmpty(this.Presenter.Schema.Name) ? "[nothing]" : this.Presenter.Schema.Name;
				this.styleName.Text = string.IsNullOrEmpty(this.Presenter.Style.Name) ? "[nothing]" : this.Presenter.Style.Name;
			}
		}
	}
}
